using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace BearGame.Singleton
{
    public static class BearSingle
    {
        public static T Get<T>() where T : class, ISingleton
        {
            return SingletonManager.Get<T>();
        }
    }

    /// <summary>
    /// 单例控制类
    /// </summary>
    public class SingletonManager : ISingleton
    {
        private static Dictionary<Type, ISingleton> _dic = new Dictionary<Type, ISingleton>();

        public Action OnAsyncInitComplete;

        public void Awake()
        {
            // DontDestroyOnLoad(this.gameObject);
            //Register(this);
        }

        public static void Register(ISingleton _type)
        {
            var type = _type.GetType();
            if (_dic.ContainsKey(type))
            {
                Debug.LogWarning($"{type.Name} already exist");
            }
            else
            {
                _dic.Add(type, _type);
                _type.OnRegister();
            }
        }

        public static void Unregister(ISingleton _type)
        {
            var type = _type.GetType();
            if (_dic.ContainsKey(type))
            {
                _dic.Remove(type);
                _type.OnCancel();
            }
            else
            {
                Debug.LogWarning($"{type.Name} not exist");
            }
        }

        /// <summary>
        /// 用于协程异步初始化组件
        /// </summary>
        /// <returns></returns>
        public IEnumerator AsyncPreInit()
        {
            foreach (var vp in _dic)
            {
                if (vp.Value != null)
                    yield return vp.Value.AsyncInit();
            }
        }

        // 统一初始化
        public void PreInit()
        {
            foreach (var vp in _dic)
            {
                if (vp.Value != null)
                    vp.Value.Init();
            }
        }

        public void CancelAll()
        {
            foreach (var vp in _dic)
            {
                if (vp.Value != null)
                    vp.Value.OnCancel();
            }

            _dic.Clear();
        }

        public static T Get<T>() where T : class, ISingleton
        {
            var type = typeof(T);

            // 使用 TryGetValue 提高性能，避免两次字典查找
            if (_dic.TryGetValue(type, out var singleton))
            {
                // 添加空值检查，防止已注册但被销毁的对象
                if (singleton != null)
                {
                    return singleton as T;
                }
                else
                {
                    // 清理无效的引用
                    _dic.Remove(type);
                    Debug.LogWarning($"Singleton of type {type.Name} was destroyed and removed from registry");
                }
            }

            return null;
        }
        
        public IEnumerator AsyncInit()
        {
            yield return null;
            OnAsyncInitComplete?.Invoke();
        }

        public void Init()
        {
            Debug.Log("SingletonManager init success");
        }

        public void OnRegister()
        {
            Debug.Log("SingletonManager register success");
        }

        public void OnCancel()
        {
            Debug.Log("SingletonManager cancel success");
        }
    }
}